package org.iartisan.maven.plugin.template;

import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.FileTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.Version;
import org.apache.maven.plugin.logging.Log;
import org.iartisan.maven.plugin.log.LoggerFactory;
import org.iartisan.maven.plugin.mavenconfig.TemplateConfig;
import org.iartisan.maven.plugin.utils.StringUtil;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

/**
 * <p>
 * 模板解析
 *
 * @author King
 * @since 2017/9/5
 */
public class TemplateParse {

    protected Configuration configuration;

    private final static String DEFAULT_TEMPLATE_PATH = "/templates/iartisan/";

    private static Log logger = LoggerFactory.getLogger();

    /**
     * 初始化模板
     *
     * @param config 配置内容
     * @throws IOException io异常
     */
    public void initConfiguration(TemplateConfig config) throws IOException {
        if (null != config) {
            Configuration cfg = new freemarker.template.Configuration(new Version("2.3.0"));
            TemplateLoader loader = null;
            if (config.getLoadPath().equals(TemplateConfig.Path.classpath.toString())) {
                loader = new ClassTemplateLoader(getClass(), !StringUtil.isEmpty(config.getTemplatePath()) ? config.getTemplatePath() : DEFAULT_TEMPLATE_PATH);
            } else if (config.getLoadPath().equals(TemplateConfig.Path.file.toString())) {
                loader = new FileTemplateLoader(new File(config.getTemplatePath()));
            }
            cfg.setTemplateLoader(loader);
            cfg.setDefaultEncoding("UTF-8");
            this.configuration = cfg;
        }
    }

    public String render(String ftlPath, Map<String, Object> data) throws IllegalAccessException, IOException, TemplateException {
        logger.info("root render dir:" + configuration.getTemplateLoader().toString());
        logger.info("render:" + ftlPath);
        Template template = configuration.getTemplate(ftlPath);
        StringWriter writer = new StringWriter();
        if (null == template) {
            throw new IllegalAccessException("先初始化template配置");
        }
        template.process(data, writer);
        return writer.toString();
    }
}
